import axios from "axios" //用axios代替ajax请求接口
import {Message} from "element-ui";
import router from "../router";


axios.interceptors.response.use(success=>{
    if(success.status && success.status==200 && success.data.status==500){
        console.log(success)
        Message.error({message:success.data.msg});
        return;
    }
    if(success.data.msg){
        Message.success({message:success.data.msg})
    }
    if (success.data.code===0){
        Message.success({message:success.data.message})
    }
    else {
        if (success.data.code){
            Message.error({message:success.data.message})
        }
    }
    return success.data;
},error => {
    // console.log("error1:"+error.response);
    // console.log("error2:"+error.response.data.msg);
    if(error.response.status ==504 || error.response.status==404){
        Message.error({message:"服务器被吃了( ╯□╰ )"})
    }else if (error.response.status == 403){
        Message.error({message:"权限不足，请联系管理员"})
    }else if (error.response.status == 401){
        router.replace('/');
        Message.error({message:"尚未登录，请登录"})
    }else {
        if (error.response.data.msg){
            Message.error({message:error.response.data.msg})
        }
        else{
            Message.error({message:"未知错误"})
        }
    }
    return;
});

let base ='/api';

export const postKeyValueRequest=(url,params)=>{
    return axios({
        method:'post',
        data:params,
        url:`${base}${url}`,
        transformRequest:[function (data) {
            let ret = '';
            for(let i in data){
                ret+=encodeURIComponent(i)+"="+encodeURIComponent(data[i])+"&"
            }
            // console.log(ret);
            return ret;
        }],
        header:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    })
};

export const postRequest=(url,params)=>{
    return axios({
        method: 'post',
        url:`${base}${url}`,
        data:params
    })
};

export const getRequest=(url,params)=>{
    return axios({
        method: 'get',
        url:`${base}${url}`,
        data:params
    })
};

export const putRequest=(url,params)=>{
    return axios({
        method: 'put',
        url:`${base}${url}`,
        data:params
    })
};

export const deleteRequest=(url,params)=>{
    return axios({
        method: 'delete',
        url:`${base}${url}`,
        data:params
    })
};